package com.filyar.htyd.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.filyar.htyd.common.Result;
import com.filyar.htyd.entity.Address;
import com.filyar.htyd.service.IAddressService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author filyar
 * @e-mail root@filyar.com
 * @since 2024-11-01
 */
@RestController
@RequestMapping("/address")
public class AddressController {

    @Resource
    private IAddressService addressService;

    private final String now = DateUtil.now();


    @PostMapping("/check")
    public Result check(@RequestBody Address address) {
        return Result.success(addressService.check(address));
    }


    @GetMapping("/getAddressCount")
    public Result getAddressCount(){
        return Result.success(addressService.count());
    }

    @GetMapping("/CompareWholeTable")
    public Result CompareWholeTable() {
        addressService.CompareWholeTable();
        return Result.success();
    }

    @PostMapping
    public Result save(@RequestBody Address address) {
        address.setCreateTime(DateTime.now());
        address.setOperator(JSON.parseObject(JSON.toJSONString(StpUtil.getSession().get("user"))).getString("nickname"));
        addressService.saveOrUpdate(address);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        addressService.removeById(id);
        return Result.success();
    }

    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        addressService.removeByIds(ids);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(addressService.getById(id));
    }

    @GetMapping("/page")
    public Result findPage(@RequestParam(defaultValue = "") String address,
                           @RequestParam Integer pageNum,
                           @RequestParam Integer pageSize) {
        LambdaQueryWrapper<Address> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.orderByDesc(Address::getId);
        if (!"".equals(address)) {
            lambdaQueryWrapper.like(Address::getAddress, address);
        }
        return Result.success(addressService.page(new Page<>(pageNum, pageSize), lambdaQueryWrapper));
    }


}

